package org.linlinjava.litemall.db.service;

import com.github.pagehelper.PageHelper;
import org.linlinjava.litemall.db.dao.LitemallCategoryMapper;
import org.linlinjava.litemall.db.domain.LitemallCategory;
import org.linlinjava.litemall.db.domain.LitemallCategoryExample;
import org.linlinjava.litemall.db.vo.CategoryTreeVo;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;

@Service
public class LitemallCategoryService {
    @Resource
    private LitemallCategoryMapper categoryMapper;
    private LitemallCategory.Column[] CHANNEL = {LitemallCategory.Column.id, LitemallCategory.Column.name, LitemallCategory.Column.iconUrl};

    public List<LitemallCategory> queryL1WithoutRecommend(int offset, int limit) {
        LitemallCategoryExample example = new LitemallCategoryExample();
        example.or().andLevelEqualTo("L1").andNameNotEqualTo("推荐").andDeletedEqualTo(false);
        PageHelper.startPage(offset, limit);
        return categoryMapper.selectByExample(example);
    }

    public List<LitemallCategory> queryL1(int offset, int limit) {
        LitemallCategoryExample example = new LitemallCategoryExample();
        example.or().andLevelEqualTo("L1").andDeletedEqualTo(false);
        PageHelper.startPage(offset, limit);
        return categoryMapper.selectByExample(example);
    }

    public List<LitemallCategory> queryL1() {
        LitemallCategoryExample example = new LitemallCategoryExample();
        example.or().andLevelEqualTo("L1").andDeletedEqualTo(false);
        return categoryMapper.selectByExample(example);
    }

    public List<LitemallCategory> queryByPid(Integer pid) {
        LitemallCategoryExample example = new LitemallCategoryExample();
        example.or().andPidEqualTo(pid).andDeletedEqualTo(false);
        return categoryMapper.selectByExample(example);
    }

    public List<LitemallCategory> queryL2ByIds(List<Integer> ids) {
        LitemallCategoryExample example = new LitemallCategoryExample();
        example.or().andIdIn(ids).andLevelEqualTo("L2").andDeletedEqualTo(false);
        return categoryMapper.selectByExample(example);
    }

    public LitemallCategory findById(Integer id) {
        return categoryMapper.selectByPrimaryKey(id);
    }

    /**
     * 根据ID查询分类及其所有子分类
     * 参考AdminCategoryController.list的实现逻辑
     * @param id 分类ID
     * @return 包含分类和子分类信息的CategoryTreeVo
     */
    public CategoryTreeVo findByIdWithChildren(Integer id) {
        // 查询当前分类
        LitemallCategory category = categoryMapper.selectByPrimaryKey(id);
        if (category == null) {
            return null;
        }
        
        CategoryTreeVo result = new CategoryTreeVo();
        
        // 设置当前分类信息
        result.setId(category.getId());
        result.setName(category.getName());
        result.setKeywords(category.getKeywords());
        result.setDesc(category.getDesc());
        result.setIconUrl(category.getIconUrl());
        result.setPicUrl(category.getPicUrl());
        result.setLevel(category.getLevel());
        result.setPid(category.getPid());
        
        // 查询子分类列表
        List<LitemallCategory> subCategoryList = queryByPid(id);
        List<CategoryTreeVo> children = new ArrayList<>();
        
        for (LitemallCategory subCategory : subCategoryList) {
            CategoryTreeVo subCategoryVo = new CategoryTreeVo();
            subCategoryVo.setId(subCategory.getId());
            subCategoryVo.setName(subCategory.getName());
            subCategoryVo.setKeywords(subCategory.getKeywords());
            subCategoryVo.setDesc(subCategory.getDesc());
            subCategoryVo.setIconUrl(subCategory.getIconUrl());
            subCategoryVo.setPicUrl(subCategory.getPicUrl());
            subCategoryVo.setLevel(subCategory.getLevel());
            subCategoryVo.setPid(subCategory.getPid());
            
            children.add(subCategoryVo);
        }
        
        result.setChildren(children);
        return result;
    }

    /**
     * 将LitemallCategory转换为CategoryTreeVo的辅助方法
     */
    private CategoryTreeVo convertToCategoryTreeVo(LitemallCategory category) {
        if (category == null) {
            return null;
        }
        
        CategoryTreeVo vo = new CategoryTreeVo();
        vo.setId(category.getId());
        vo.setName(category.getName());
        vo.setKeywords(category.getKeywords());
        vo.setDesc(category.getDesc());
        vo.setIconUrl(category.getIconUrl());
        vo.setPicUrl(category.getPicUrl());
        vo.setLevel(category.getLevel());
        vo.setPid(category.getPid());
        
        return vo;
    }

    /**
     * 查询完整的分类树（包含所有子分类）
     * @param id 分类ID
     * @return 分类及其子分类列表的Map结构
     */
    public Map<String, Object> findCategoryTree(Integer id) {
        // 查询当前分类
        LitemallCategory category = categoryMapper.selectByPrimaryKey(id);
        if (category == null) {
            return null;
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("category", category);
        
        // 查询子分类
        List<LitemallCategory> children = queryByPid(id);
        result.put("children", children);
        
        // 如果需要递归查询更深层级的子分类
        List<Map<String, Object>> childrenWithSubChildren = new ArrayList<>();
        for (LitemallCategory child : children) {
            Map<String, Object> childMap = new HashMap<>();
            childMap.put("category", child);
            
            // 查询子分类的子分类
            List<LitemallCategory> subChildren = queryByPid(child.getId());
            childMap.put("children", subChildren);
            
            childrenWithSubChildren.add(childMap);
        }
        result.put("childrenTree", childrenWithSubChildren);
        
        return result;
    }

    public List<LitemallCategory> querySelective(String id, String name, Integer page, Integer size, String sort, String order) {
        LitemallCategoryExample example = new LitemallCategoryExample();
        LitemallCategoryExample.Criteria criteria = example.createCriteria();

        if (!StringUtils.isEmpty(id)) {
            criteria.andIdEqualTo(Integer.valueOf(id));
        }
        if (!StringUtils.isEmpty(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        criteria.andDeletedEqualTo(false);

        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }

        PageHelper.startPage(page, size);
        return categoryMapper.selectByExample(example);
    }

    public int updateById(LitemallCategory category) {
        category.setUpdateTime(LocalDateTime.now());
        return categoryMapper.updateByPrimaryKeySelective(category);
    }

    public void deleteById(Integer id) {
        categoryMapper.logicalDeleteByPrimaryKey(id);
    }

    public void add(LitemallCategory category) {
        category.setAddTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        categoryMapper.insertSelective(category);
    }

    public List<LitemallCategory> queryChannel() {
        LitemallCategoryExample example = new LitemallCategoryExample();
        example.or().andLevelEqualTo("L1").andDeletedEqualTo(false);
        return categoryMapper.selectByExampleSelective(example, CHANNEL);
    }
}
